*WHAT'S ACROSS THE BORDER?
*JHA, NEUMARK, AND RODRIGUEZ-LOPEZ

include directories.do


* Load stacked pair data at the county or czone-state level
use "`popdir'`s'countypairs_years_pop.dta", clear


ren cty_fips county


********* MERGE  PAIRS ********************

merge m:1 countypair_id county using "`countydir'`s'countypairtypes.dta"

keep if _merge==3
 
drop _merge

*KEEP ONLY THOSE PAIRS WITH FULL DATA ALL YEARS

foreach h in  "totpop" {

bys countypair year: egen `h'_pair=total(`h')

}


collapse (first) countypair_id totpop_pair type0-type5 (min) countymin=county (max) countymax=county, by(countypair year)



foreach j in "1" "2" "3" "4" "5" {
bys year: egen npairstotpop`j'=count(countypair) if type`j'==1
sum npairstotpop`j'
}


foreach h in "totpop" {
gen l`h'_pair=log(`h'_pair)
foreach j in "1" "2" "3" "4" "5" {
bys year: egen sum`h'_pair`j'=total(`h'_pair) if type`j'==1 
gen avg`h'_pair`j'=sum`h'_pair`j'/(npairs`h'`j'*1000)
}
}

drop sum*


collapse (min) avg* npairs*, by(year)


foreach h in "totpop" {
twoway (line avg`h'_pair5 year, lpattern(dash) lc(blue)) (line avg`h'_pair1 year, lc(blue)) (line avg`h'_pair2 year, lc(red)) (line avg`h'_pair3 year,  lc(red) lpattern(dash)) (line avg`h'_pair4 year,  lc(red) lpattern(shortdash)), legend(off)  xtitle("Year") scheme(s1color) xlabel(1991 1995 1999 2003 2007 2011 2015 , valuelabel) ylabel(100 125 150 175 200 225 250 275) ytitle("Average population per pair (thousands)")
gr export "`outfigdir'`s'figureC1R.eps", replace
}

tempfile avg_pair
save `avg_pair'


* Load stacked pair data at the county or czone-state level
use "`popdir'`s'countypairs_years_pop.dta", clear
ren cty_fips county


collapse (first) totpop multi, by(county year)

bys county: egen multi2=max(multi)

drop multi 
ren multi2 multi

********* MERGE  PAIRS ********************

merge m:1 county using "`countydir'`s'countytypes.dta"
keep if _merge==3
drop _merge


foreach f in "totpop" {
foreach j in "1" "2" "3" "4" "5" {
bys year: egen `f'`j'=total(`f') if type`j'==1
}
}



foreach j in "1" "2" "3" "4" "5" {
bys year: egen ncounties`j'=count(county) if type`j'==1
sum ncounties`j'
}


collapse (min) totpop1-totpop5 ncounties1-ncounties5, by(year)
drop if year==.

foreach f in "totpop" {
foreach j in "1" "2" "3" "4" "5" {
gen avg`f'_co`j'=`f'`j'/(ncounties`j'*1000) 
}
}

merge 1:1 year using `avg_pair'
drop _merge

twoway (line avgtotpop_co5 year, lpattern(dash) lc(blue)) (line avgtotpop_co1 year, lc(blue)) (line avgtotpop_co2 year, lc(red)) (line avgtotpop_co3 year,  lc(red) lpattern(dash)) (line avgtotpop_co4 year,  lc(red) lpattern(shortdash)), legend(off)  xtitle("Year") scheme(s1color) xlabel(1991 1995 1999 2003 2007 2011 2015 , valuelabel) ylabel(55 65 75 85 95 105 115 125)  ytitle("Average population per county (thousands)")
gr export "`outfigdir'`s'figureC1L.eps", replace

clear all


